<template>
<div>
  <h1>销售统计</h1>
  <fieldset>
    <legend>图书销售统计</legend>
    <el-table
      :data="bookSales"
      border
      show-summary
      :summary-method="getSummaries"
      style="width: 100%">
      <el-table-column prop="isbn" label="ISBN"> </el-table-column>
      <el-table-column prop="name" label="书名"> </el-table-column>
      <el-table-column prop="count" sortable label="销售量"> </el-table-column>
      <el-table-column prop="amount" sortable label="销售额" :formatter="priceFormat"> </el-table-column>
    </el-table>
  </fieldset>
</div>
</template>

<script>
import { AdminGetSalesStat } from '@/utils/request'
import { int2price } from '@/utils/format'

export default {
  data () {
    return {
      bookSales: []
    }
  },
  methods: {
    priceFormat (row, column, cellValue, index) {
      return int2price(cellValue, true)
    },
    getSummaries (param) {
      const { columns, data } = param
      let sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[3] = int2price(sums[3])
        } else {
          sums[index] = ''
        }
      })

      return sums
    }
  },
  created () {
    AdminGetSalesStat().then(rsp => {
      this.bookSales = rsp.data
    })
  }
}
</script>

<style lang="scss" scoped>

</style>
